package com.linxianqin.aop.aspect;

import com.linxianqin.aop.annotion.TestAop;
import com.linxianqin.aop.utils.IPUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * 功能描述：
 *
 * @author lxq
 * @version 1.00
 * @Date 2020/12/11
 */
@Slf4j
@Component
@Aspect
public class TestAopAspect {
    //切入点
    @Pointcut("@annotation(com.linxianqin.aop.annotion.TestAop)")
    public void pointcut(){}

    @Before("pointcut()")
    public void doBefore(JoinPoint joinPoint)throws Throwable{
        log.info("doBefore");
    }

    @Around("@annotation(testAop)")
    public Object around(ProceedingJoinPoint pjp, TestAop testAop) {
        //获取注解里的值
        log.info("around:{}" , testAop.desc());
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        }
    }
    @After("pointcut()")
    public void doAfter(JoinPoint joinPoint)throws Throwable{
        log.info("doAfter");
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info("URL : {}" , request.getRequestURL().toString());
        log.info("HTTP_METHOD : {}" , request.getMethod());
        log.info("IP : {}" , IPUtil.getIpAddr(request));
        log.info("CLASS_METHOD : {}" , joinPoint.getSignature().getDeclaringTypeName());
        log.info("ARGS : {}" , Arrays.toString(joinPoint.getArgs()));
    }

}
